<?php
class UsersController extends AppController {
    public $helpers = array('Html', 'Form');
    public $uses = array('User', 'Recipe','Follow','Comment');
    
    public function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow('register','userCenter');
    }

    public function index(){
        if ($this->Session->read('userid')) {
            $this->redirect(array('action' => 'userCenter'));
        }else{
            $this->redirect(array('controller'=>'recipe','action' => 'view'));
        }
    }
    
    public function register(){
        if ($this->request->is('post')) {
            $this->User->create();
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash(__('注册成功'));
                $this->redirect(array('action' => 'login'));
            } else {
                $this->Session->setFlash(__('注册失败，请重试'));
            }
        }
    }
    
    public function userCenter($userId = null) {
        if($userId == null){
            $userId = $this->Session->read('userid');
        }
        if (!$userId) {
            //throw new NotFoundException(__('Invalid post'));
            $this->redirect(array('controller'=>'users','action' => 'login'));
        }
        
        // $data = $this->paginate = array(
        //         'limit' => 9,
        //         'conditions' => array(
        //             'userId' => $userId
        //             ),
        //         'recursive' => 0,
        //         'order'=>'recipe.id DESC'
        // );

        $data = $this->paginate('Recipe');                  
        $this->set('posts',$data);
        
        $this->set('user',$this->User->findById($userId));
    }
    
    public function modifyUser() {
        $user = $this->User->findById($this->Session->read('userid'));
        if ($this->request->is('post') || $this->request->is('put')) {
            $this->User->id = $this->Session->read('userid');

            if ($this->User->saveField('url',$this->request->data['User']['url'])) {
                $this->Session->setFlash('用户资料修改成功');
                $this->Session->write('userurl',$this->request->data['User']['url']);
            } else {
                $this->Session->setFlash('用户资料修改失败');
            }
        }

        if (!$this->request->data) {
            $this->request->data = $user;
        }
    }

    public function modifyRecipe($recipeId=null){
        if (!$recipeId) {
            throw new NotFoundException(__('Invalid post'));
        }
        
        $recipe = $this->Recipe->findById($recipeId);
        
        if ($this->request->is('post') || $this->request->is('put')) {
            if ($this->Recipe->save($this->request->data)) {
                $this->Session->setFlash('食谱修改成功');
            } else {
                $this->Session->setFlash('食谱修改失败');
            }
            $this->redirect(array('controller'=>'users','action' => 'userCenter'));
        }

        if (!$this->request->data) {
            $this->request->data = $recipe;
        }

    }

    public function addFollow($toId=null){
        if (!$toId) {
            throw new NotFoundException(__('Invalid post'));
        }
        
        $fromId = $this->Session->read('userid');
        $id = $this->Follow->findByFromAndTo($fromId, $toId);
        if ($id) {
            $this->Session->setFlash(__('您已经关注了Ta.'));
            $this->redirect(array('controller'=>'users','action' => 'userCenter',$toId));
        }
        //if ($this->request->is('post')) {
            $this->Follow->create();
            $data = array('from' => $fromId, 'to' => $toId);
            if ($this->Follow->save($data)) {
                $this->Session->setFlash(__('关注成功'));
            } else {
                $this->Session->setFlash(__('关注失败，请重试'));
            }
        //}

        $this->redirect(array('controller'=>'users','action' => 'userCenter',$toId));
    }

    public function deleteFollow($id=null){
        if (!$id) {
            throw new NotFoundException(__('Invalid post'));
        }
        $follow = $this->Follow->findById($id);
        $fromId = $this->Session->read('userid');
        if($fromId == $follow['Follow']['from']){
            $this->Follow->delete($id);
            $this->Session->setFlash(__('解除关注成功'));
        }
        else{
            $this->Session->setFlash(__('解除关注失败'));
        }

        $this->redirect(array('controller'=>'users','action' => 'viewFollow'));
    }
    
    public function viewFollow(){   
        $fromId = $this->Session->read('userid');
        
        $this->paginate = array(
                'limit' => 20,
                'conditions' => array(
                    'from' => $fromId
                    ),
                    'recursive' => 0
        );

        $this->set('user',$this->User->findById($fromId));
        $data = $this->paginate('Follow');                  
        $this->set('follows',$data);
    }

    public function viewFriendRecipes() {
        
        $userId = $this->Session->read('userid');
        $this->set('user',$this->User->findById($userId));
        $this->paginate = array(
                'limit' => 20,
                    'recursive' => -1,
                    'joins' => array(array(
                                    'alias' => 'Follow',
                                    'table' => 'follow',
                                    'conditions' => 'Follow.to = Recipe.userId and Follow.from ='.$userId,
                                    'type' => 'INNER',
                                    )), 
        );

        $data = $this->paginate('Recipe');                  
        $this->set('posts',$data);
    }

    public function login(){
        if ($this->request->is('post')) {
            if ($this->Auth->login()) {
                $myuser = $this->User->findByUsername($this->request->data['User']['username']);
                $this->Session->write('username',$this->request->data['User']['username']);
                $this->Session->write('userid',$myuser['User']['id']);
                $this->Session->write('userurl',$myuser['User']['url']);
                $this->Session->write('usergroup',$myuser['User']['group']);
                $this->redirect($this->Auth->redirect());
            } else {
                $this->Session->setFlash(__('用户名/密码错误'));
            }
        }       
    }

    public function grant(){
        $group = $this->Session->read('usergroup');
        if ($group == 0){
             $this->Session->setFlash(__('您没有权限。'));
             $this->redirect(array('controller'=>'Users','action'=>'userCenter'));
        }

        if ($this->request->is('post')) {
            if ($this->request->data('action') == "add"){
                $this->Session->setFlash($this->request->data('username'));
                
                $user = $this->User->findByUsername($this->request->data('username'));
                if (!$user) {
                    $this->Session->setFlash('没有找到该用户');
                }
                else
                {
                    $this->User->id = $user['User']['id'];
                    if ($this->User->saveField('group',1)) {
                        $this->Session->setFlash('添加管理员成功');
                    } else {
                        $this->Session->setFlash('添加管理员失败');
                    }
                }
            }
            if ($this->request->data('action') == "del"){

            }
        }
        
        $data = $this->User->find('all',array('recursive'=>0,'conditions'=>array('group'=>1)));
        $report['usersNumber'] = $this->User->query('SELECT COUNT(*) FROM user')[0][0]['COUNT(*)'];
        $report['recipesNumber'] = $this->Recipe->query('SELECT COUNT(*) FROM recipe')[0][0]['COUNT(*)'];
        $report['commentsNumber'] = $this->Comment->query('SELECT COUNT(*) FROM comment')[0][0]['COUNT(*)'];
        $this->set('report',$report);
        $this->set('users',$data);
    }
       
        
    public function logout(){
        $this->Session->destroy();
        $this->redirect($this->Auth->logout());
        $this->Session->setFlash(__('注销成功'));
    }
        
}
    
?>
